package com.pai.servlet;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.pai.vo.ApiResult;


import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

/**
 * @author amu_1115@126.com
 * @version 1.0
 */
public class BaseServlet extends HttpServlet {

    /**
     * 转发请求
     * @param request
     * @param response
     * @param path
     * @throws ServletException
     * @throws IOException
     */
     public void doDispatch(HttpServletRequest request, HttpServletResponse response, String path)throws ServletException, IOException{
         RequestDispatcher dispatcher =request.getRequestDispatcher(path);
         dispatcher.forward(request,response);
     }

    /**
     * 重定向
     * @param request
     * @param response
     * @param url
     * @throws ServletException
     * @throws IOException
     */
    public void doRedirect(HttpServletRequest request, HttpServletResponse response, String url)throws ServletException, IOException{
       response.sendRedirect(url);
    }

    /**
     *
     * @param response
     * @param result
     */
    protected  void write(HttpServletResponse response, ApiResult result)throws IOException {
        //一些对响应的基础设置
        response.setContentType("application/json;charset=utf-8");
        response.setCharacterEncoding("utf-8");
        //设置跨域请求共享
        //各个部分是干什么的，暂不深究
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Credentials", "true");
        response.setHeader("Access-Control-Allow-Methods", "*");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers", "Authorization,Origin,X-Requested-With,Content-Type,Accept,content-Type,origin,x-requested-with,content-type,accept,authorization,token,id,X-Custom-Header,X-Cookie,Connection,User-Agent,Cookie,*");
        response.setHeader("Access-Control-Request-Headers", "Authorization,Origin, X-Requested-With,Content-Type,Accept");
        //这里，正式把我们得到的API响应处理成json形式，然后放入响应中，让响应带回去
        //应该是这样吧
        String jsonStr= JSON.toJSONString(result);
        response.getWriter().write(jsonStr);
        response.getWriter().flush();
        response.getWriter().close();  //关闭流？我记得好像是
    }


    /**
     * 获取前端传过来的json值
     * @param req
     * @return
     */
    public String getJsonString(HttpServletRequest req) {

        //自定义从bodyt中获取json格式数据
        StringBuffer sb = new StringBuffer();
        String line = null;
        try {
            BufferedReader reader = req.getReader();
            while ((line = reader.readLine()) != null)
                sb.append(line);
        } catch (Exception e) { /*report an error*/ }
        //将空格和换行符替换掉避免使用反序列化工具解析对象时失败
//        String jsonString = sb.toString().replaceAll("\\s","").replaceAll("\n","");
        String jsonString = sb.toString();
        //下面就可以使用如GSON或FastJson之类的工具解析成自己的对象数据并做后续的业务逻辑处理了

//        返回结果
//        PrintWriter out = response.getWriter();
//        out.write("success");
//        out.close();
        return jsonString;

    }

}
